PROJ	:= 8
EMPTY	:=
SPACE	:= $(EMPTY) $(EMPTY)
SLASH	:= /
V 		:= @
.SUFFIXES: .c .S .h

EXE_PATH = /usr/bin
PREFIX = arm-none-eabi-
GCCPREFIX = $(EXE_PATH)/$(PREFIX)
CC = $(GCCPREFIX)gcc

AR = $(GCCPREFIX)ar
LD      := $(GCCPREFIX)ld
OBJCOPY := $(GCCPREFIX)objcopy
OBJDUMP := $(GCCPREFIX)objdump

COPY	:= cp
MKDIR   := mkdir -p
MV		:= mv
RM		:= rm -f
AWK		:= awk
SED		:= sed
SH		:= sh
TR		:= tr
TOUCH	:= touch -c

ALLOBJS	:=
ALLDEPS	:=
TARGET	:= rt_thread

include tools/function.mk

DEVICE = -march=armv7-a -marm -msoft-float
CFLAGS = $(DEVICE) -Wall
CFLAGS += -g -gdwarf-2 -nostartfiles -nostdlib
INCLUDE += 	include/ \
			include/libc/ \
			include/drivers/ \
			include/ipc/ \
			boot/arm/cortex-a/ \
			boot/arm/common/ \
			boot/bsp/
			
CFLAGS += $(addprefix -I,$(INCLUDE))

M_CFLAGS = $(CFLAGS)  -mlong-calls -fPIC 
LDFLAGS	= -T link.lds 



OBJDIR	:= obj
BINDIR	:= bin
CTYPE	:= c S
RSTYPE  := rs

SRCDIR = 	boot/arm/common  \
			boot/arm/cortex-a \
			boot/bsp \
			components/serial

listf_cc = $(call listf,$(1),$(CTYPE))
listf_rs = $(call listf,$(1),$(RSTYPE))

build: $(TARGET).elf

cgtype = $(patsubst %.$(2),%.$(3),$(1))
objfile = $(call toobj,$(1))
asmfile = $(call cgtype,$(call toobj,$(1)),o,asm)
outfile = $(call cgtype,$(call toobj,$(1)),o,out)
symfile = $(call cgtype,$(call toobj,$(1)),o,sym)

bootfiles = $(call listf_cc,$(SRCDIR))
$(foreach f,$(bootfiles),$(call cc_compile,$(f),$(CC),$(CFLAGS) -Os ))

$(call finish_all)

bootblock = $(call totarget,bootblock)

start_gcc.o:boot/start_gcc.S
	$(CC) -c boot/start_gcc.S -o start_gcc.o $(CFLAGS)

vector_gcc.o: boot/vector_gcc.S
	$(CC) -c $< -o $@ $(CFLAGS)

lds: vector_gcc.o start_gcc.o 
	$(LD) $(LDFLAGS) -o start.elf $^

$(bootblock): $(call toobj,$(bootfiles))

rust_src = $(call listf_rs, rt_kernel/src/*)

librtsrc.a: $(rust_src)
	@ echo 'cargo build'
	$(V) cd rt_kernel && cargo build
	$(V) cp rt_kernel/target/armv7a-none-eabi/debug/librtsrc.a ./

$(TARGET).elf: $(bootblock) librtsrc.a
	$(LD) $(LDFLAGS) -o $(TARGET).elf $(call toobj,$(bootfiles)) -L./ -lrtsrc -nostdlib
	
	
.PHONY: clean qemu-dbg qemu

qemu: $(TARGET).elf
	qemu-system-arm -M vexpress-a9 -m 128M -kernel $(TARGET).elf -serial stdio

qemu-dbg: $(TARGET).elf
	qemu-system-arm -M vexpress-a9 -m 128M -kernel $(TARGET).elf -serial stdio -S -s &
	sleep 1
	gnome-terminal -e "/opt/gcc-arm-none-eabi-6_2-2016q4/bin/arm-none-eabi-gdb -q -x gdbfile"

clean:
	-$(V) rm -r obj 
	cd rt_kernel && cargo clean
	rm $(TARGET).elf
	rm librtsrc.a
